package com.ruoyi.prod.controller;

import com.github.pagehelper.Page;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.prod.entity.dto.ProdPurchaseDTO;
import com.ruoyi.prod.entity.po.ProdAsset;
import com.ruoyi.prod.entity.query.ProdPurchaseCondition;
import com.ruoyi.prod.enums.LogModuleEnum;
import com.ruoyi.prod.enums.LogTypeEnum;
import com.ruoyi.prod.service.BaseLogService;
import com.ruoyi.prod.service.ProdAssetService;
import com.ruoyi.prod.service.ProdPurchaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 采购管理 - 采购进度
 *
 * @author BaiBan
 * @since 2023/2/18
 */
@Api(tags = "采购管理-采购进程")
@RestController
@RequestMapping("/prod/purchase/process")
public class ProdPurchaseProcessController {

    @Autowired
    private ProdPurchaseService baseService;

    @Autowired
    private BaseLogService logService;

    @Autowired
    private ProdAssetService assetService;

    /**
     * 详情
     */
    @ApiOperation("详情")
    @GetMapping("/{id}")
    public R<ProdPurchaseDTO> getInfo(@PathVariable String id) {
        return R.ok(baseService.getProcess(id));
    }

    /**
     * 分页
     */
    @ApiOperation("分页")
    @PostMapping("/page")
    public R<List<ProdPurchaseDTO>> page(@Validated @RequestBody ProdPurchaseCondition condition) {
        Page<ProdPurchaseDTO> page = baseService.page(condition);
        return R.page(page.getResult(), page.toPageInfo());
    }

    /**
     * 新增
     */
    @ApiOperation("新增")
    @PostMapping("/add")
    public R<?> add(@Validated @RequestBody ProdPurchaseCondition condition) {

        // TODO 日志 需要改
        String content = "新增数量:" + condition.getFinishNumber();
        logService.save(condition.getId(), LogModuleEnum.PURCHASE, LogTypeEnum.PURCHASE, content);

        List<ProdAsset> list = assetService.save(condition);

        // TODO 日志 需要改
        List<String> ids = list.stream().map(ProdAsset::getId).collect(Collectors.toList());
        logService.saveBatch(ids, LogModuleEnum.ASSET, LogTypeEnum.COMMIT);

        return R.ok(null, "新增成功");
    }
}
